#pragma once

namespace wc
{
	template<class T>
	struct list_node
	{
		list_node<T>* _next;
		list_node<T>* _prev;
		T _data;
		list_node(const T& x = T())
			:_next(nullptr)
			,_prev(nullptr)
			,_data(x)
		{ }
	};

	template<class T,class Ref, class Ptr>
	struct list_iterator
	{
		typedef list_node<T> Node;
		typedef list_iterator<T, Ref, Ptr> Self;
		Node* _node;

		list_iterator(Node* node)
			:_node(node)
		{}

		Ref operator*() {
			return _node->_data;
		}
		Ptr operator->() {
			return &_node->_data;
		}
		Self& operator++() {  
			_node = _node->_next;
			return *this;
		}
		Self& operator--() {
			_node = _node->_prev;
			return *this;
		}
		Self& operator++(int) {
			_node = _node->_next;
			return *this;
		}
		Self& operator--(int) {
			_node = _node->_prev;
			return *this;
		}
		bool operator!=(const Self& other) {
			return _node != other._node;
		}
		bool operator==(const Self& other) {
			return _node == other._node;
		}
	};

	template<class T>
	class list
	{
		typedef list_node<T> Node;
	public:
		typedef list_iterator<T,T&,T*> iterator;
		typedef list_iterator<T,const T&,const T*> const_iterator;
		iterator begin() {
			return iterator(_head->_next);
		}
		iterator end() {
			return iterator(_head);
		}
		list() 
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
		}
		
		
		void push_back(const T& x){
			//Node* newnode = new Node(x);
			//Node* tail = _head->_prev;
			//tail->_next = newnode;
			//newnode->_prev = tail;
			//newnode->_next = _head;
			//_head->_prev = newnode;
			insert(end(), x);
		}
		void push_front(const T& x) {
			insert(begin(), x);
		}
		void pop_front() {
			erase(begin());
		}
		void pop_back() {
			erase(--end());
		}
		void insert(iterator pos, const T& x) {
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			Node* newnode = new Node(x);
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;
			cur->_prev = newnode;
		}
		iterator erase(iterator pos) {
			assert(pos != end());
			Node* cur = pos._node;
			Node* nextNode = cur->_next;
			Node* prevNode = cur->_prev;
			prevNode->_next = nextNode;
			nextNode->_prev = prevNode;
			return iterator(nextNode);
		}

	private:
		Node* _head;
	};
}